package spring.boot.server.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spring.boot.server.codec.InvocationDecoder;
import spring.boot.server.codec.InvocationEncoder;
import spring.boot.server.dispatcher.MessageDispatcher;

import java.util.concurrent.TimeUnit;

@Component
public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {

    @Autowired
    private MessageDispatcher messageDispatcher;

    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Override
    protected void initChannel(Channel channel) {
        //心跳检测 设定IdleStateHandler心跳检测每五秒进行一次读检测，如果五秒内ChannelRead()方法未被调用则触发一次userEventTrigger()方法
        channel.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
        // 编码器
        channel.pipeline().addLast(new InvocationEncoder());
        // 解码器
        channel.pipeline().addLast(new InvocationDecoder());
        // 消息分发器
        channel.pipeline().addLast(messageDispatcher);
        // 服务端处理器
        channel.pipeline().addLast(nettyServerHandler);
    }
}
